/**
 * Created by Freeman on 2018/1/20.
 */
import {LOG_IN_SUCCESS, LOG_OUT_SUCCESS, USER_INFO_SUCCESS} from "../../constants/ActionTypes";
import {Alert} from "react-native";
import {getApi, postApi} from '../../api/common'
import jwtDecode from 'jwt-decode'

export const login = value => async dispatch => {
  value = {...value, rememberme: true}
  const {data} = await postApi('/user/oauth/token', value)
  dispatch({
    type: LOG_IN_SUCCESS,
    token: data.access_token,
    isLogged: true,
  })
  return dispatch(fetchUserInfo(jwtDecode(data.access_token).user_id))
}

export const fetchUserInfo = id => async dispatch => {
  const {data} = await getApi(`/user/profiles/${id}`)
  return dispatch({
    type: USER_INFO_SUCCESS,
    userInfo: data,
  })
}

export const logout = () => dispatch => {
  return getApi(`/user/oauth/logout`)
    .then(() => {
      dispatch({
        type: LOG_OUT_SUCCESS,
      })
    }).catch(error => {
      Alert.alert(JSON.stringify(error))
    })
}
